package com.qf.shiroboot.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisSessionDAO extends AbstractSessionDAO {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    private final String SHIRO_SESSION = "SHIRO_SESSION:";

    // 创建
    @Override
    protected Serializable doCreate(Session session) {
        System.out.println("将Session保存到Redis");
        //1. 生成SessionID.
        Serializable sessionId = super.generateSessionId(session);

        //2. 绑定SessionID和Session对象
        super.assignSessionId(session,sessionId);

        //3. 将数据存储到Redis中
        redisTemplate.opsForValue().set(SHIRO_SESSION + sessionId,session,30, TimeUnit.MINUTES);

        //4. 返回sessionId
        return sessionId;
    }

    // 读取
    @Override
    protected Session doReadSession(Serializable sessionId) {
        System.out.println("从Redis中读取Session");
        //1. 获取Session对象
        Session session = (Session) redisTemplate.opsForValue().get(SHIRO_SESSION + sessionId);

        if(session != null) {
            //2. 重新设置生存时间
            redisTemplate.expire(SHIRO_SESSION + sessionId,30, TimeUnit.MINUTES);
        }

        //3. 返回Session对象
        return session;
    }

    // 修改
    @Override
    public void update(Session session) throws UnknownSessionException {
        System.out.println("更新Redis中的Session");
        //1. 通过Session获取SessionId
        Serializable sessionId = session.getId();
        //2. 设置到Redis中
        redisTemplate.opsForValue().set(SHIRO_SESSION + sessionId,session,30, TimeUnit.MINUTES);
    }

    @Override
    public void delete(Session session) {
        // delete
    }

    @Override
    public Collection<Session> getActiveSessions() {
        // keys scan
        return null;
    }
}
